package org.yds.quality.function.dft;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorRuntimeJavaType;
import org.yds.quality.model.DefectResultDTO;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Dft extends AbstractFunction {
    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject totalObj, AviatorObject conditionObj) {
        // 获取参数值
        long total = (long) totalObj.getValue(env); // total 是 SumIf 的返回值
        String condition = (String) conditionObj.getValue(env);

        // 从 env 中获取满足条件的 glassId 列表

        String code = (String) env.get("code");

        // 将 total 和 code 放入局部环境
        Map<String, Object> localEnv = new HashMap<>(env);
        localEnv.put("count", total);
        localEnv.put("code", code);

        // 执行逻辑表达式
        boolean success = (boolean) AviatorEvaluator.execute(condition, localEnv);
        List<String> dftGlassIds = new ArrayList<>();
        if (success) {
            dftGlassIds = (List<String>) env.get("dftGlassIds");
        }
        // 返回自定义对象
        return new AviatorRuntimeJavaType(new DefectResultDTO(success, (int) total, code, dftGlassIds));
    }

    @Override
    public String getName() {
        return "Dft";
    }
}
